const express = require('express')
const cors = require('cors')
const app = express()
const session = require('express-session')
const path = require('path')

// 设置可以访问的源
const ORIGIN = new Set(['http://127.0.0.1:8080'])

app.use((req, res, next) => {
	const origin = req.headers.origin
	if (ORIGIN.has(origin)) {
		// 设置可以携带 cookie
		res.header('Access-Control-Allow-Credentials', true)
		// 第二个参数表示允许跨域的域名
		res.header('Access-Control-Allow-Origin', origin)
		res.header(
			'Access-Control-Allow-Methods',
			'GET, POST, PUT, DELETE, OPTIONS, HEAD'
		)
		res.header(
			'Access-Control-Allow-Headers',
			'Content-Type, Authorization, Origin, Content-Length, X-Requested-With'
		)
		if (req.method == 'OPTIONS') {
			res.sendStatus(200)
		} else {
			next()
		}
	} else {
		res.status(403).send({
			message: '你没有权限访问相应资源',
		})
	}
})

// 处理 'application/json' 类型的数据
app.use(express.json())

// 处理 'application/x-www-form-urlencoded' 类型的数据
app.use(express.urlencoded({ extended: true }))

// 使用 express 中间件，保存用户会话信息
app.use(
	session({
		secret: 'secret',
		name: 'coonect_id',
		rolling: true,
		resave: false,
		saveUninitialized: true,
		cookie: {
			maxAge: 1000 * 60 * 60 * 24,
		},
	})
)

require('./router')(app)

//404 处理
app.get('*', (req, res) => {
	return res.status(404).send({
		message: '找不到页面',
	})
})

// set port, listen for requests
const PORT = process.env.PORT || 8083
app.listen(PORT, () => {
	console.log(`服务在 ${PORT} 端口启动.`)
})
